"""

    Lamptop development utilities
    Copyright (C) 2011  Colby T. Sollars

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
"""

from base import lamptopCliAction_base
import lamptop_util
import os
import os.path
from config import *
    
class lamptopCliAction_createVirtualhost(lamptopCliAction_base):
    def __init__(self, app):
        lamptopCliAction_base.__init__(self, app)
        self.vhost_util = lamptop_util.lamptopVirtualhost(self.app)
        
    def do_action(self, subcommand="", options=[]):
        lamptopCliAction_base.do_action(self)
        hostname = self._get_validated_input(
            "Enter virtualhost hostname: ",
            "WHOOPS! The name you provided didn't work for the following reasons:",
            self.vhost_util.validate_new_hostname
        )
        hostname_parts = hostname.split(".")
        subdomain = ""
        if len(hostname_parts) > 2:
            subdomain = '.'.join(hostname_parts[:-2])
        else:
            subdomain = hostname_parts[0]
        suggested_path = self.app.config.default_root_directory + subdomain
        if os.path.exists(suggested_path):
            suggested_path_str = ""
        if suggested_path:
            suggested_path_str = ' [' + suggested_path + ']'
        document_root = self._get_validated_input(
            "Enter document root" + suggested_path_str + ": ",
            "WHOOPS! The file path you entered didn't work for the following reasons:",
            self.vhost_util.validate_new_root_path,
            suggested_path
        )
        
        return self.vhost_util.create_virtualhost(hostname, document_root,\
        self.app.config.host_file_path, self.app.config.localhost_ip,\
        self.app.config.web_user, self.app.config.web_group)
    
    def failure_message(self, errors):
        lamptopCliAction_base.failure_message(self, errors)
        print "WHOOPS! Failed to create new virtualhost for the following reasons:"
        for err in errors:
            print "    " + err
    
    def success_message(self):
        lamptopCliAction_base.success_message(self)
        print "\nNew project built. Please restart Apache to use new virtualhost"

    def show_help(self):
        print "usage: lamptop create_virtualhost\n"
        print "Creates a new Apache virtualhost. It will ask you interactively for any needed info\n"
